package com.bdqn.jwt1.util;

import com.bdqn.jwt1.entity.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component("jwtLoginFailureHandler")
public class JwtLoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        String errorMsg = "";
        if (exception instanceof UsernameNotFoundException) {
            errorMsg = "用户名不存在";
        } else if (exception instanceof LockedException) {
            errorMsg = "用户被冻结";
        } else if (exception instanceof BadCredentialsException) {
            errorMsg = "用户名或密码错误";
        } else {
            errorMsg = exception.getMessage();
        }
        //将错误信息写入ResponseResult-
        ResponseResult sr = new ResponseResult();
        sr.setCode(2);
        sr.setErrorMsg(errorMsg);
        sr.setFlag(false);
        String s = objectMapper.writeValueAsString(sr);
        response.getWriter().write(s);
    }
}
